package org.xg.study.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName CountServlet
 * @date 2021/9/23 15:53
 **/
@WebServlet("/countServlet")
public class CountServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = super.getServletContext();
        Integer count = (Integer) context.getAttribute("count");
        context.setAttribute("count",++count);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("<h3>xg www.ocmg.top welcome</h3>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    public void init() throws ServletException {
        //获取ServletContext对象
        ServletContext context = getServletContext();
        //初始化时，向ServletContext中设置count属性，初始值为0
        context.setAttribute("count", 0);
    }
}
